##########################################
## Copyright 2012-2013 Ceruti Francesco & contributors
##
## This file is part of LiSP (Linux Show Player).
##########################################

from PyQt4 import QtCore
from PyQt4 import QtGui
from lisp.ui.preferences.preferences_widget import PreferencesWidget
from lisp.ui.qtextinputdialog import QTextInputDialog
from lisp.midi.midi import midiDevicesList


class General(PreferencesWidget):

    NAME = 'General'

    def __init__(self, size, parent=None):
        super(General, self).__init__(size, parent)

        self.verticalLayoutWidget = QtGui.QWidget(self)
        self.verticalLayoutWidget.setGeometry(QtCore.QRect(0, 0, 431, 310))
        self.verticalLayout = QtGui.QVBoxLayout(self.verticalLayoutWidget)
        self.verticalLayout.setMargin(10)

        self.useDefaultLayout = QtGui.QCheckBox(self.verticalLayoutWidget)
        self.verticalLayout.addWidget(self.useDefaultLayout)

        self.selectDefaultLayout = QtGui.QComboBox(self.verticalLayoutWidget)
        self.verticalLayout.addWidget(self.selectDefaultLayout)

        self.verticalLayout.addSpacing(20)

        self.useDefaultDevice = QtGui.QCheckBox(self.verticalLayoutWidget)
        self.verticalLayout.addWidget(self.useDefaultDevice)

        self.midiSelect = QtGui.QComboBox(self.verticalLayoutWidget)
        self.verticalLayout.addWidget(self.midiSelect)

        self.devices = []
        for d in midiDevicesList():
            dev = '[' + d[0] + '] ' + d[1]
            dev += ' -> open' if(d[4]) else ' -> close'
            self.devices.append(dev)
            if(d[2]):
                self.midiSelect.addItem(dev)

        self.verticalLayout.addSpacing(20)

        self.useStandAloneTheme = QtGui.QCheckBox(self.verticalLayoutWidget)
        self.verticalLayout.addWidget(self.useStandAloneTheme)

        self.verticalLayout.addSpacing(20)

        self.pipelineEdit = QtGui.QPushButton(self.verticalLayoutWidget)
        self.verticalLayout.addWidget(self.pipelineEdit, 3)

        self.verticalLayout.addSpacing(20)

        self.horizontalLayoutWidget = QtGui.QWidget(self.verticalLayoutWidget)
        self.horizontalLayout = QtGui.QHBoxLayout(self.horizontalLayoutWidget)
        self.horizontalLayout.setMargin(0)

        self.horizontalLayout.addSpacing(50)

        self.warningImage = QtGui.QLabel(self.horizontalLayoutWidget)
        self.warningImage.setPixmap(QtGui.QIcon.fromTheme("dialog-warning").pixmap(QtCore.QSize(24, 24)))
        self.horizontalLayout.addWidget(self.warningImage)

        self.warning = QtGui.QLabel(self.horizontalLayoutWidget)
        self.warning.setText(" <b>Need application restart</b>")
        self.warning.setSizePolicy(QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Fixed))
        self.horizontalLayout.addWidget(self.warning)

        self.verticalLayout.addWidget(self.horizontalLayoutWidget, 3)

        self.useDefaultLayout.toggled.connect(self.selectDefaultLayout.setEnabled)
        self.useDefaultDevice.toggled.connect(self.midiSelect.setDisabled)
        self.pipelineEdit.clicked.connect(self.editPipeline)

        self.retranslateUi()

    def retranslateUi(self):
        self.useDefaultLayout.setText('Use default layout')
        self.useStandAloneTheme.setText('Use stand-alone (dark) theme')
        self.pipelineEdit.setText("Default Pipeline - Only for Advanced Users")
        self.useDefaultDevice.setText('Use default MIDI device')

    def getConfiguration(self):
        conf = {'Layout': {}, 'Themes': {}, 'GStreamer': {}, 'MIDI': {}}

        conf['Layout']['usedefault'] = str(self.useDefaultLayout.isChecked())
        conf['Layout']['default'] = self.selectDefaultLayout.currentText()
        conf['Themes']['usestandalonetheme'] = str(self.useStandAloneTheme.isChecked())
        if(self.oldPipeline != self.pipeline):
            if(self.pipeline.strip() != ''):
                conf['GStreamer']['defaultpipeline'] = self.pipeline
            elif(self.oldPipeline != ''):
                conf['GStreamer']['defaultpipeline'] = self.oldPipeline
        if(self.useDefaultDevice.isChecked()):
            conf['MIDI']['deviceid'] = '-1'
        else:
            conf['MIDI']['deviceid'] = str(self.devices.index(self.midiSelect.currentText()))

        return conf

    def setConfiguration(self, conf):
        if(conf is None):
            self.setEnabled(False)
        elif('GStreamer' not in conf
             or 'Layout' not in conf
             or 'MIDI' not in conf):
            self.setEnabled(False)
        else:
            if('usedefault' in conf['Layout']):
                self.useDefaultLayout.setChecked(conf['Layout']['usedefault'] == 'True')
                self.selectDefaultLayout.setEnabled(conf['Layout']['usedefault'] == 'True')
            if('packages' in conf['Layout']):
                pkgs = conf['Layout']['packages'].split(',')
                self.selectDefaultLayout.addItems(pkgs)
                if('default' in conf['Layout']):
                    self.selectDefaultLayout.setCurrentIndex(pkgs.index(conf['Layout']['default']))
            if('usestandalonetheme' in conf['Themes']):
                self.useStandAloneTheme.setChecked(conf['Themes']['usestandalonetheme'] == 'True')
            if('defaultpipeline' in conf['GStreamer']):
                self.pipeline = conf['GStreamer']['defaultpipeline']
                self.oldPipeline = self.pipeline
            else:
                self.pipelineEdit.setEnabled(False)
            if('deviceid' in conf['MIDI']):
                if(int(conf['MIDI']['deviceid']) < 0):
                    self.useDefaultDevice.setChecked(True)
                    self.midiSelect.setEnabled(False)
                elif(len(self.devices) > int(conf['MIDI']['deviceid'])):
                    for n in range(self.midiSelect.count()):
                        if(self.midiSelect.itemText(n) == self.devices[int(conf['MIDI']['deviceid'])]):
                            self.midiSelect.setCurrentIndex(n)
                            self.devices[int(conf['MIDI']['deviceid'])] += ' {current}'
                            self.midiSelect.setItemText(n, self.devices[int(conf['MIDI']['deviceid'])])

    def editPipeline(self):
        editUi = QTextInputDialog(initial=self.pipeline, parent=self)
        editUi.exec_()

        if(editUi.result() == QtGui.QDialog.Accepted):
            self.pipeline = editUi.plainTextEdit.toPlainText()
